package util.web;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import role.RoleDao;
import role.RoleDaoImpl;

public class AuthorityFilter implements Filter{
	private RoleDao roleDao=new RoleDaoImpl(); 
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		String url = request.getServletPath();
		if(request.getSession().getAttribute("user")==null){
			while(roleDao.findById(1l).getRole_authority().iterator().hasNext()){
				if(url.equals(roleDao.findById(1l).getRole_authority().iterator().next().getAuthority_url_no())){
					break;
				}
			}
			response.sendRedirect("/login.action");
		}else{
			request.getSession().getAttribute("user");
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
